package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.COOKIE_NAME;
import static com.leyou.auth.constants.RedisConstants.JTI_KEY_PREFIX;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private final UserClient userClient;
    private final JwtUtils jwtUtils;
    private final StringRedisTemplate redisTemplate;

    public UserServiceImpl(UserClient userClient, JwtUtils jwtUtils, StringRedisTemplate redisTemplate) {
        this.userClient = userClient;
        this.jwtUtils = jwtUtils;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        // 1.远程调用ly-user，校验用户名和密码
        UserDTO user = null;
        try {
            user = userClient.queryUserByUsernameAndPassword(username, password);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.contentUTF8());
        }
        // 2.判断查询结果
        if(user == null){
            // 3.如果错误，抛出异常
            throw new LyException(400, "用户名或密码错误");
        }
        // 4.如果正确，生成JWT
        String jwt = jwtUtils.createJwt(UserDetails.of(user.getId(), user.getUsername()));
        // 5.把JWT写入cookie
        writeCookie(response, jwt);
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 1.获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if(jwt == null){
            return;
        }
        try {
            // 2.解析jwt，获取用户信息
            Payload payload = jwtUtils.parseJwt(jwt);
            UserDetails userDetail = payload.getUserDetail();
            // 3.删除redis中的jti
            redisTemplate.delete(JTI_KEY_PREFIX + userDetail.getId());
        } catch (Exception e) {
            log.debug("解析jwt失败，无需退出登录");
        }
        // 4.删除cookie
        CookieUtils.deleteCookie(COOKIE_NAME, JwtConstants.DOMAIN, response);
    }

    private void writeCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
        cookie.setPath("/");
        cookie.setDomain(JwtConstants.DOMAIN);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }
}
